package main

import (
	"flag"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gen"
	"gorm.io/gorm"
	"k9-panel/app/model"
	"k9-panel/config"
	"path/filepath"
	"runtime"
)

// Dynamic SQL
type Querier interface {
	// SELECT * FROM @@table WHERE name = @name{{if role !=""}} AND role = @role{{end}}
	FilterWithNameAndRole(name, role string) ([]gen.T, error)
}

var (
	File     string
	ShowHelp bool
)

func init() {
	flag.StringVar(&File, "config", "", "config file")
	flag.BoolVar(&ShowHelp, "help", false, "show help")
	flag.Parse()

	_, err := config.LoadConfig(File)

	if err != nil {
		panic(err)
	}
	// listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
func main() {
	_, filePath, _, ok := runtime.Caller(0)
	if !ok {
		fmt.Println("Failed to get file path")
		return
	}

	dir := filepath.Dir(filePath)
	g := gen.NewGenerator(gen.Config{
		OutPath: filepath.Join(dir, "../../app/query"),
		Mode:    gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface, // generate mode
	})

	gDB, _ := gorm.Open(mysql.Open(config.Cfg.DSN))
	_ = gDB.AutoMigrate(model.Project{}, model.Environment{}, model.BaseConfig{}, model.DerivedConfig{}, model.HistoryConfig{}, model.ProjectEnvironment{}, model.UserToken{}, model.Account{})

	g.UseDB(gDB) // reuse your gorm db

	// Generate basic type-safe DAO API for struct `model.User` following conventions
	g.ApplyBasic(model.Project{}, model.Environment{}, model.BaseConfig{}, model.DerivedConfig{}, model.HistoryConfig{}, model.ProjectEnvironment{}, model.UserToken{}, model.Account{})

	// Generate Type Safe API with Dynamic SQL defined on Querier interface for `model.User` and `model.Company`
	g.ApplyInterface(func(Querier) {}, model.Project{}, model.Environment{}, model.BaseConfig{}, model.DerivedConfig{}, model.HistoryConfig{}, model.ProjectEnvironment{}, model.UserToken{}, model.Account{})

	// Generate the code
	g.Execute()
}
